<template>
  <div class="upload-container">
    <el-button icon='el-icon-upload' size="mini" :style="{background:color,borderColor:color}"
               @click="handleUpload" type="primary">上传图片
    </el-button>
    <el-dialog append-to-body :visible.sync="dialogVisible">
      <el-upload class="editor-slide-upload"
                 :action="uploadApi"
                 list-type="picture-card"
                 :multiple="true"
                 :file-list="fileList"
                 :show-file-list="true"
                 :on-remove="handleRemove"
                 :limit="limit"
                 :on-success="handleSuccess"
                 :before-upload="beforeUpload"
                 :on-exceed="handleExceed"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" :disabled="forbidDoubleClick" @click="handleSubmit">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from 'api/qiniu'
import Cookies from 'js-cookie';

export default {
  name: 'editorSlideUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff',
    },
    limit: {
      type: Number,
      default: 5,
    },
    contentType: {
      type: Number,
      default: undefined,
    },
    imgList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      uploadApi: `${api.UPLOAD_PIC}?token=${Cookies.get(consts.CACHE_TOKEN)}&uid=${Cookies.get(consts.CACHE_UID)}`,
      dialogVisible: false,
      listObj: {},
      fileList: [],
      fileListCopy: [],
      forbidDoubleClick: true,
    };
  },
  methods: {
    checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess);
    },
    handleSubmit() {
      this.forbidDoubleClick = true;
      const arr = [];
      const arr1 = Object.keys(this.listObj).map(v => this.listObj[v]);
      arr.push(...this.fileListCopy, ...arr1);
      while (arr.length > 3) { // 防止操作过快，删除图片的操作还没执行完
        arr.shift();
      }
      if (!this.checkAllSuccess()) {
        this.$message('请等待所有图片上传成功 或 图片格式不正确 或 出现了网络问题，请刷新页面重新上传！');
        this.forbidDoubleClick = false;
        return;
      }
      this.$emit('successCBK', arr);
      this.$emit('input', _.map(arr, picInfo => picInfo.url, //  '/'+
      ));
      this.listObj = {};
      this.fileList = [];
      this.fileListCopy = [];
      this.dialogVisible = false;
    },
    handleSuccess(response, file) {
      if (response.code === 1) {
        const { uid } = file;
        response = response.data;
        const objKeyArr = Object.keys(this.listObj);
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            this.listObj[objKeyArr[i]].url = response;
            this.listObj[objKeyArr[i]].hasSuccess = true;
            return;
          }
        }
      } else {
        this.$notify.error(response.message);
      }
    },
    handleRemove(file) {
      const { uid } = file;
      const index = _.findIndex(this.fileListCopy, { uid });
      if (index > -1) { // 判断若是原有图片列表中的数据则删除原有列表中的数据
        this.fileListCopy.splice(index, 1);
        return;
      }
      const objKeyArr = Object.keys(this.listObj);
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (Number(objKeyArr[i]) === uid) {
          delete this.listObj[objKeyArr[i]];
        }
      }
    },
    handleCancel() {
      this.dialogVisible = false;
      this.listObj = {};
      this.fileList = [];
      this.fileListCopy = [];
    },
    handleUpload() {
      this.dialogVisible = true;
      this.forbidDoubleClick = false;
      this.listObj = {};
      if (!_.isEmpty(this.imgList)) {
        this.fileList = this.imgList.map(item => item);
        this.fileListCopy = _.cloneDeep(this.fileList);
      } else {
        this.fileList = [];
        this.fileListCopy = [];
      }
    },
    beforeUpload(file) {
      const _self = this;
      const _URL = window.URL || window.webkitURL;
      const fileName = file.uid;
      this.listObj[fileName] = {};
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = _URL.createObjectURL(file);
        img.onload = function () {
          _self.listObj[fileName] = {
            hasSuccess: false, uid: file.uid, width: this.width, height: this.height,
          };
        };
        resolve(true);
      });
    },
    handleExceed(files, fileList) {
      this.$notify.error(`图片数量超出限制，最多上传${this.limit}张`);
    },
  },
};
</script>

<style lang="scss" scoped>
  .editor-slide-upload {
    margin-bottom: 20px;
  }
</style>
